﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 车辆相关
    /// </summary>
    public class CarController : BaseApiController
    {
        CarService _service = new CarService();
        CarCheckService _carCheckService = new CarCheckService();
        MainTenanceService _mainTenanceService = new MainTenanceService();
        VehicleViolationService _vehicleService = new VehicleViolationService();
        VehicleRemindService _vehRemindService = new VehicleRemindService();

        /// <summary>
        /// 根据车型ID获取车款列表
        /// </summary>
        /// <param name="SerialId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<Car>> GetCarListBySeriesId(int SerialId)
        {
            ResultData<List<Car>> result = ResultData<List<Car>>.Success("查询成功");
            if (SerialId <= 0)
            {
                result.status = -1;
                result.message = "缺少必须的参数SerialId";
            }
            var list = _service.GetCarListBySerialId(SerialId);
            result.data = list;
            return result;
        }

        /// <summary>
        /// 获取验车
        /// </summary>
        /// <param name="vehicleId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<CarCheck>> GetCarChecks(int vehicleId)
        {
            var data = _carCheckService.GetCarChecks(vehicleId);
            return ResultData<List<CarCheck>>.Success(data);
        }

        /// <summary>
        /// 获取保养里程
        /// </summary>
        /// <param name="vehicleId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<MainTenance>> GetMainTenances(int vehicleId)
        {
            var data = _mainTenanceService.GetMainTenances(vehicleId);
            return ResultData<List<MainTenance>>.Success(data);
        }

        /// <summary>
        /// 获取违章记录
        /// </summary>
        /// <param name="vehicleId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<VehicleViolation>> GetVehicles(int vehicleId)
        {
            var data = _vehicleService.GetVehicles(vehicleId);
            return ResultData<List<VehicleViolation>>.Success(data);
        }

        /// <summary>
        /// 添加验车
        /// </summary>
        /// <param name="check"></param>
        /// <returns></returns>
        public ResultData<int> AddCarCheck(CarCheck check)
        {
            check.IsActive = 1;
            check.CreatedDate = DateTime.Now;
            check.NextCheckDate = check.CheckDate.AddYears(1);
            object id = _carCheckService.Insert(check);
            return ResultData<int>.Success(Convert.ToInt32(id));
        }

        /// <summary>
        /// 添加保养里程
        /// </summary>
        /// <param name="tenance"></param>
        /// <returns></returns>
        public ResultData<int> AddMainTenance(MainTenance tenance)
        {
            tenance.IsActive = 1;
            tenance.CreatedDate = DateTime.Now;
            object id = _mainTenanceService.Insert(tenance);
            return ResultData<int>.Success(Convert.ToInt32(id));
        }

        /// <summary>
        /// 设置车辆提醒
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultData<int> SetVehicleRemind(VehicleRemindModel model)
        {
           
            ResultData<int> result = ResultData<int>.Error("操作失败");
            if (model.VehicleLicenseID <= 0)
            {
                result.message = "行驶证ID不能为空";
                return result; 
            }
            if (model.ReMindType<=0||model.ReMindType>4)
            {
                result.message = "请正确填写要设置的提醒";
                return result;
            }
            bool isAdd = false;
            VehicleRemind vrObj = _vehRemindService.GetInfoByVehicleID(model.VehicleLicenseID);
            if (vrObj == null)
            {
                vrObj = new VehicleRemind();
                vrObj.VehicleLicenseID = model.VehicleLicenseID;
                vrObj.CreatedDate = DateTime.Now;
                vrObj.IsActive = 1;
                vrObj.NextMaintainDate = DefultTime;
                vrObj.MaintainDate = DefultTime;
                vrObj.NextInsureDate = DefultTime;
                vrObj.InsureExpireDate = DefultTime;
                vrObj.NextYearCheckDate = DefultTime;
                vrObj.FirstRegisterDate = DefultTime;
                isAdd = true;
            }
            if (model.ReMindType == 1)
            {
                vrObj.IsViolate = model.IsViolate;
                vrObj.EngineCode = model.EngineCode;
            }
            if (model.ReMindType == 2)
            {
                vrObj.IsYearCheck = model.IsYearCheck;
                vrObj.FirstRegisterDate = model.FirstRegisterDate;
                vrObj.NextYearCheckDate = GetLittleCarYearCheckDate(vrObj.FirstRegisterDate);
            }
            if (model.ReMindType == 3) 
            {
                vrObj.IsInsure = model.IsInsure;
                vrObj.InsureExpireDate = model.InsureExpireDate;
                DateTime dt = DateTime.Now;
                if (model.InsureExpireDate <= dt)
                {
                    TimeSpan ts = new System.TimeSpan(dt.Ticks - model.InsureExpireDate.Ticks);
                    vrObj.NextInsureDate = model.InsureExpireDate.AddYears((ts.Days / 365) + 1);
                }
                else
                {
                    vrObj.NextInsureDate = model.InsureExpireDate;
                }
            }
            if (model.ReMindType == 4)
            {
                vrObj.IsMaintain = model.IsMaintain;
                vrObj.MaintainDate = model.MaintainDate;
                vrObj.MaintainPeriod = model.MaintainPeriod;
                vrObj.NextMaintainDate = GetNextMaintainDate(vrObj);
            }
            try
            {
                if (isAdd)
                {
                    _vehRemindService.Insert(vrObj);
                }
                else
                {
                    _vehRemindService.Update(vrObj);
                }
                return ResultData<int>.Success("设置成功");
            }
            catch (Exception ex)
            {
                result.message = string.Format("设置失败,{0}",ex.Message);
                return result;
            }
         
        }

        /// <summary>
        /// 获取车辆提醒
        /// </summary>
        /// <param name="vehId"></param>
        /// <returns></returns>
        public ResultData<VehicleRemind> GetVehicleRemind(int vehId)
        {

            ResultData<VehicleRemind> result = ResultData<VehicleRemind>.Error("获取失败");
            if (vehId <= 0)
            {
                result.message = "行驶证ID不能为空";
                return result;
            }
            try
            {
                VehicleRemind vrObj = _vehRemindService.GetInfoByVehicleID(vehId);
                if (vrObj != null)
                {
                    if (vrObj.IsMaintain==1)
                    {
                        
                    }
                    if (vrObj.IsYearCheck==1)
                    {
                       
                    }
                    result.data = vrObj;
                    result.status = 0;
                    result.message = "成功";
                }
                return result;
            }
            catch (Exception ex)
            {
                result.message = string.Format("获取失败,{0}", ex.Message);
                return result;
            }

        }

        private DateTime GetNextMaintainDate(VehicleRemind vrObj)
        {
            DateTime dt = vrObj.MaintainDate.AddDays(vrObj.MaintainPeriod);
            DateTime nowDt = DateTime.Now;
            if (dt < nowDt)
            {
                int span = (nowDt - vrObj.MaintainDate).Days / vrObj.MaintainPeriod + 1;
                dt = vrObj.MaintainDate.AddDays(vrObj.MaintainPeriod * span);
            }
           
            return dt;
        }

        /// <summary>
        /// 获取小客车年检时间
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DateTime GetLittleCarYearCheckDate(DateTime dt)
        {
            DateTime newDt = DateTime.Now;
            int year = newDt.Year - dt.Year;

            if (year <= 6)
            {
                if (dt.AddYears(6) >= newDt.Date)
                {
                    return dt.AddYears(6);
                }
                else
                {
                    return dt.AddYears(7);
                }

            }
            else if (year > 6 && year < 15)
            {
                if (dt.AddYears(year) >= newDt.Date)
                {
                    return dt.AddYears(year);
                }
                else
                {
                    return dt.AddYears(year + 1);
                }

            }
            else
            {
                if (year == 15)
                {
                    if (dt.Month < 7)
                    {
                        int m = 6;
                        if (newDt.Month - dt.Month > 6)
                        {
                            m = 12;
                        }
                        else if (newDt.Month - dt.Month == 6 && newDt.Day > dt.Day)
                        {
                            m = 12;
                        }
                        return dt.AddYears(year).AddMonths(m);
                    }
                    else
                    {
                        if (dt.AddYears(year) >= newDt.Date)
                        {
                            return dt.AddYears(year);
                        }
                        else
                        {
                            return dt.AddYears(year).AddMonths(6);
                        }
                    }

                }
                else
                {
                    return dt.AddYears(year).AddMonths(6);
                }
            }

        }
    }
}
